import React, { useEffect, useState } from 'react'
import ShowDrawer from '@/components/ShowDrawer'
import {
    Form,
    Input,
    Tree,
    message,
} from 'antd';
import './style.less'
import { remoteList } from '@/api/system/menu'
import { addInfo,updateInfo } from '@/api/system/role';
import { rules } from './rules'
import { IRole } from '../types';
import { IMenu } from '../../menu/types';
import { deepClone } from '@/utils';

const Info = (props: any) => {
    const { info } = props;
    const fieldNames = {
        children: 'children',
        title: 'menuName',
        key: 'path'
    }
    //初始化表单
    let initForm = {
        roleName: '',
        menus: []
    }
    const [form] = Form.useForm<IRole>();
    const [infoForm, setInfoForm] = useState<IRole>({ ...initForm, ...info });
    const [treeData, setTreeData] = useState<Array<IMenu>>([])
    const [checkedKeys, setCheckedKeys] = useState<Array<any>>();
    const [allKeys,setAllKeys] = useState<Array<any>>()

    useEffect(() => {
        let { menus = [] } = info;
        showRoutes(menus);
    }, [])

    //提交表单
    const onFinish = async () => {
        form.validateFields().then(async values => {
            let sendForm = {...infoForm,...values}
            if(allKeys){
                sendForm.menus = allKeys
            }
            if (sendForm.roleId) {
                //编辑
                await updateInfo(sendForm);
            } else {
                //新增addInfo
                await addInfo(sendForm);
            }
            message.success('操作成功');
            form.resetFields();
            props.submit();
        }).catch(info => {
            console.log('Validate Failed - ', info);
        });
    }
    //选择项
    const onCheckSelect = (selectedKeys: any, info: { halfCheckedKeys?: any; }):void => {
        let allKeys = [...selectedKeys,...info.halfCheckedKeys];
        setAllKeys(allKeys);
        setCheckedKeys(selectedKeys)
    }

    //显示选中路由菜单
    const showRoutes = async (menus: Array<IMenu>) => {
        let data = await getMenus();
        if (!menus.length) return [];
        let routes = dealRoutes(menus,data);
        setCheckedKeys(routes);
    }
    //处理父层级 选中 子层级为全选
    const dealRoutes = (routes: Array<IMenu>,treeData:Array<IMenu>) => {
        if (!treeData.length) return [];
        dealMenuChecked(treeData, routes)
        let res = dealChecked(treeData, routes)
        return res
    }
    const dealMenuChecked = (treeData:Array<IMenu>,routes:Array<IMenu>)=>{
        if(treeData?.length){
            treeData.map((item:any)=>{
                item.childNum = 0;
                if(item.children?.length){
                    item.children.map((child: { path: IMenu; })=>{
                        if(routes.indexOf(child.path)!=-1){
                            item.childNum +=1
                        }
                    })
                    item.children = dealMenuChecked(item.children,routes)
                }else{
                    if(routes.indexOf(item.path)!=-1){
                        item.childNum +=1
                    } 
                }
            })
        }
        return treeData;
    }
    const dealChecked = (treeData: any[],menus: IMenu[])=>{
        let menusArray = deepClone(menus);
        if(treeData?.length){
            treeData.map(item=>{
                if(item.children?.length){
                    if(item.childNum!=0 && item.childNum<item.children.length){
                        menusArray = menusArray.filter((route: any)=>route!=item.path)
                        menusArray = dealChecked(item.children,menusArray)
                    }
                }
            })
        }
        return menusArray
    }
    //获取菜单列表
    const getMenus = async () => {
        try {
            let res = await remoteList({});
            let { data } = res;
            setTreeData(data)
            return data
        } finally {
        }
    }

    return (
        <ShowDrawer
            close={() => props.close()}
            submit={() => onFinish()}>
            <Form
                form={form}
                name="info"
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                initialValues={{ remember: false }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item label="角色名称" name="roleName" initialValue={infoForm.roleName} rules={rules.roleName}>
                    <Input placeholder="请输入角色名称" />
                </Form.Item>
                <Form.Item label="角色权限" name="menus" initialValue={infoForm.menus} rules={rules.menus}>
                    <Tree
                        checkable
                        defaultExpandAll={false}
                        fieldNames={fieldNames}
                        treeData={treeData}
                        defaultExpandParent
                        checkedKeys={checkedKeys}
                        onCheck={onCheckSelect}
                    />
                </Form.Item>
            </Form>
        </ShowDrawer>
    )


}
export default Info
